<template>
  <div style="margin-top: 50px;">
    <el-row :gutter="15">
      <el-form ref="elForm" :model="formData"  size="medium" label-width="100px">
        <el-col :span="16">
          <el-form-item label="通知1" prop="notice">
            <el-input v-model="formData.notice" :maxlength="120" clearable :style="{width: '60%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="通知2" prop="noticeo">
            <el-input v-model="formData.noticeo" :maxlength="120" clearable :style="{width: '60%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="通知3" prop="noticet">
            <el-input v-model="formData.noticet" :maxlength="120" clearable :style="{width: '60%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="通知4" prop="notices">
            <el-input v-model="formData.notices" :maxlength="120" clearable :style="{width: '60%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="通知5" prop="noticef">
            <el-input v-model="formData.noticef" :maxlength="120" clearable :style="{width: '60%'}">
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="16">
          <el-form-item label="标题" prop="topo">
            <el-input v-model="formData.topo" :maxlength="120" clearable :style="{width: '60%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="内容" prop="topt">
            <el-input v-model="formData.topt" :maxlength="120" clearable :style="{width: '60%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="按钮文字" prop="tops">
            <el-input v-model="formData.tops" :maxlength="120" clearable :style="{width: '60%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="图片" prop="imgs" >

          <el-upload
            action="#"
            ref="uploadRef"
            list-type="picture-card"
            :auto-upload="false"
            :limit="4"
            :on-exceed="handleExceed"
            :before-upload="beforeUpload"
            :on-change="handleChange"
            :on-remove="handleRemove"
            :file-list="fileList"
            :http-request="customUpload">

            <!-- 上传按钮显示逻辑 -->
            <div >
              <i class="el-icon-plus"></i>
            </div>

          </el-upload>
          </el-form-item>
        </el-col>

        <el-col :span="16">
          <el-form-item label="内容1" prop="titleo">
            <el-input v-model="formData.titleo" :maxlength="120" clearable :style="{width: '60%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="时间1" prop="dateo">
            <el-date-picker
              v-model="formData.dateo"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="内容2" prop="titlet">
            <el-input v-model="formData.titlet" :maxlength="120" clearable :style="{width: '60%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="时间2" prop="datet">
            <el-date-picker
              v-model="formData.datet"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="16">
          <el-form-item label="内容3" prop="titles">
            <el-input v-model="formData.titles" :maxlength="120" clearable :style="{width: '60%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="时间3" prop="dates">
            <el-date-picker
              v-model="formData.dates"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="内容4" prop="titlef">
            <el-input v-model="formData.titlef" :maxlength="120" clearable :style="{width: '60%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="时间4" prop="datef">
            <el-date-picker
              v-model="formData.datef"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item size="large">
            <el-button type="primary" @click="submitForm"   :loading="isSubmitting" >提交</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
  </div>
</template>
<script>
  import { getData  ,upload,add,update} from "@/api/system/dotificationpictures";
export default {
  components: {},
  props: [],
  data() {
    return {
      isSubmitting: false,
      formData: {
        id:'',
        imgs:[],
        notice:''
      },
      fileList: []
    }
  },
  computed: {},
  watch: {},
  created() {
     this.getData();
  },
  mounted() {

  },
  methods: {
    getData() {
      getData().then(response => {
        this.formData = response.data ? response.data : {}
        if(this.formData){
          this.fileList  = this.formData.imgs.map(url  => ({
            name: url.split('/').pop(),
            url: process.env.VUE_APP_BASE_API + url
          }));
        }
      });
    },

    // 文件类型/大小校验
       beforeUpload(file) {
          const isImage = /\.(jpg|jpeg|png|gif)$/i.test(file.name);
          if (!isImage) {
            this.$message.error(' 只能上传图片格式!');
             this.isSubmitting  =  false;
            return false;
          }
            const hasChinese = /[\u4e00-\u9fa5]/.test(file.name);
             if (hasChinese) {
               this.$message.error(' 文件名不能包含中文！');
               this.isSubmitting  =  false;
               return false; // 阻止上传
             }
         return true;
       },
      // 文件变化时生成预览
        handleChange(file,fileList) {
           this.fileList  = fileList; // 更新列表状态
        },
 // 删除操作
        handleRemove(file, fileList) {
            this.fileList  = fileList;
                // 1.把删除的图片url地址 去掉http://192.168.xxx.xx:8080 头部
                // 2.去实际上传的 form.contextImg 去掉这条数据
                const str = file.url;
                let delStr = str.replace(process.env.VUE_APP_BASE_API, "");
                // console.log("delStr=>", delStr);
                for (let i = 0; i < this.formData.imgs.length; i++) {
                  if (this.formData.imgs[i] == delStr) {
                    this.formData.imgs.splice(i, 1);
                  }
                }
                // console.log("删除时候form.contextImg", this.form.contextImg);
        },
        // 自定义上传方法
        customUpload(params) {
          const data = new FormData();
           this.fileList.forEach(file  => {
                data.append('files',  file.raw);  // 文件字段名需与后端对齐
              });
          upload(data).then(response => {
            console.log(response)
             // 更新回显 URL（替换临时路径）
                  this.fileList  = this.fileList.map(item  => ({
                    ...item,
                    url: response.urls[item.uid]  // 假设后端返回路径映射
                  }));
            this.formData.imgs.push(...response.urls);
            this.submit()
          });
        },
  submitForm() {
      // 如果正在提交，直接返回
          if (this.isSubmitting)  return;

          // 锁定按钮状态
          this.isSubmitting  = true;
    const files = this.$refs.uploadRef.uploadFiles;
    const a = files.some(item  => item.status  === 'ready');
      if (files.length  > 0 && a  ) {
          this.$refs.uploadRef.submit();
      }else{
        this.submit()
      }
    },
    submit(){
      this.$refs['elForm'].validate(valid => {
        if (!valid)
        return
        // TODO 提交表单
        if(!this.formData.id){
          add(this.formData).then(response => {
            this.$modal.msgSuccess("保存成功");
            this.fileList  = [];
             this.getData()
              // 解锁按钮状态
                     this.isSubmitting  = false;
          });
        }else{
          update(this.formData).then(response => {
            this.$modal.msgSuccess("保存成功");
            this.fileList  = [];
             this.getData()
              // 解锁按钮状态
                     this.isSubmitting  = false;
          });
        }

      })
    },
        // 超出数量限制处理
        handleExceed() {
          this.$message.warning(' 只能上传4张图片');
        },

  }
}

</script>
<style>
.el-upload__tip {
  line-height: 1.2;
}
</style>
